package com.exchange.used.config.utils;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;

public class CsvUtil {

    private final static Logger LOGGER = Logger.getLogger(CsvUtil.class.getName());

    public static Writer write(List<List<String>> datas,
                               File csvFile,
                               Integer skipRows,
                               Integer skipCols,
                               String charsetName) {
        BufferedWriter out = null;
        if (!csvFile.isFile()) {
            throw new RuntimeException("excel file is not exist !");
        }
        if (datas == null || datas.size() == 0) {
            throw new RuntimeException("data can not be null !");
        }
        if (skipRows == null) {
            skipRows = 0;
        }
        if (skipCols == null) {
            skipCols = 0;
        }
        if (skipRows < 0 || skipCols < 0) {
            throw new RuntimeException("skip rows or cols can not less than 0 !");
        }
        try {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), charsetName));
            for (int i = 0; i < skipRows; i++) {
                out.newLine();
            }
            for (int i = 0; i < datas.size(); i++) {
                for (int j = 0; j < skipCols; j++) {
                    out.write(",");
                }
                List<String> rowData = datas.get(i);
                for (int j = 0; j < rowData.size(); j++) {
//                    out.write(DelQuota(rowData.get(j)));
                    out.write(rowData.get(j));
                    out.write(",");
                }
                out.newLine();
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.warning(e.getMessage());
        }
        return out;
    }

    public static String DelQuota(String str) {
        String result = str;
        String[] strQuota = {"~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "`", ";", "'", ",", ".", "/", ":", "/,", "<", ">", "?"};
        for (int i = 0; i < strQuota.length; i++) {
            if (result.indexOf(strQuota[i]) > -1)
                result = result.replace(strQuota[i], "");
        }
        return result;
    }

    public static List<List<String>> read(String path) {
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8"));
            List<List<String>> alldata = new ArrayList<>();
            String line;
            String[] onerow;
            while ((line = in.readLine()) != null) {
                onerow = line.split(",");  //默认分割符为逗号，可以不使用逗号
                List<String> onerowlist = Arrays.asList(onerow);
                List<String> onerowaArrayList = new ArrayList<>(onerowlist);
                alldata.add(onerowaArrayList);
            }
            in.close();
            return alldata;
        } catch (Exception e) {
            return null;
        }

    }

    public static InputStream read(List<List<String>> datas) {
        if(datas == null || datas.size() == 0){
            throw new RuntimeException("data can not be null !");
        }
        StringBuilder sb = new StringBuilder();
        InputStream is = null;
        try {
            for(List<String> row : datas){
                for(String s : row){
                    sb.append(s);
                    sb.append(",");
                }
                sb.deleteCharAt(sb.length() - 1);
                sb.append('\n');
            }
            is = new ByteArrayInputStream(sb.toString().getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return is;
    }
}
